<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>6-Promise常用API-对象方法</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <style></style>
  </head>
  <body>
    <div id="app"></div>
    <script>
      function getData(url) {
        return new Promise(function (resolve, reject) {
          var xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function () {
            if (xhr.readyState != 4) return;
            if (xhr.readyState == 4 && xhr.status == 200) {
              resolve(xhr.responseText);
            } else {
              reject('服务器未知错误！');
            }
          };
          xhr.open('get', url);
          xhr.send(null);
        });
      }

      var proA = getData('http://localhost:3000/a1');
      var proB = getData('http://localhost:3000/b1');
      var proC = getData('http://localhost:3000/c1');

      // // Promise.all结果一起返回： 等待3秒之后，一起返回了数据
      // Promise.all([proA, proB, proC]).then(function (res) {
      //   console.log(res); //Array(3) [ "Hello a1", "Hello b1", "Hello c1" ]
      // });

      // Promise.race，只要有一个结果返回来了，后续的就返回不了，只有第一个结果返回
      Promise.race([proA, proB, proC]).then(function (res) {
        console.log(res); //Hello a1
      });
    </script>
  </body>
</html>
